<template>
  <div>
    <el-dialog :title="title" :visible.sync="addVisible" width="580px">
      <el-form ref="addForm" :model="addForm" :rules="rules" size="medium" :inline="true" label-width="92px" class="addform">
        <div class="textLine">
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="addForm.phone" placeholder="请输入号码" style="width: 260px"></el-input>
          </el-form-item>
          <el-form-item label="获客平台" prop="platformId">
            <el-select v-model="addForm.platformId" placeholder="请选择获客平台" clearable style="width: 260px">
              <el-option :label="item.scrmGetGuestPlatName" :value="item.scrmGetGuestPlatId" v-for="item in platformList" :key="item.scrmGetGuestPlatId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="textLine weGroupTagVOS">
          <el-form-item label="标签" prop="weGroupTagVOS">
            <tag-group v-model="addForm.weGroupTagVOS" maxWidth="300px" />
          </el-form-item>
        </div>
        <div class="textLine" style="margin-top:8px">
          <el-form-item prop="distributeEmploye" label="分配员工" class="showRedRules">
            <el-button class="button-new-tag" size="small" @click="handleClick">
              <svg-icon icon-class="add" />
              添加员工
            </el-button>
            <div v-if="scrmPersonSopUserRels.length > 0">
              <el-tag v-for="item in scrmPersonSopUserRels" :key="item.userId" closable @close="handleClose(item)">
                {{ item.userName || item.name || ''}}
              </el-tag>
            </div>
          </el-form-item>
        </div>
        <div class="textLine">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="addForm.remark" placeholder="请添加备注" style="width: 360px" id="remarkInput" :autosize="{ minRows: 3 }" :maxlength="64" @input="remarkChange"></el-input>
            <span id="remarkInputNum">{{ this.remarkInputNum }}/64</span>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="handelConfirm" v-preventReClick="1000">确定
        </el-button>
      </div>
    </el-dialog>
    <SelectUser :selectList="tableDataName" :visible.sync="selectUserVisible" :userList="[]" @confirm="selectUserConfirm" :is-active="'1'"></SelectUser>
  </div>
</template>
<script>
import { add, updateAdding } from '@/api/beathAdd'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import SelectCus from '@/views/customerOperations/attractCustomers/component/selectCus.vue'
import SelectUser from '@/components/SelectUser/index.vue'
import MakeLabel from '@/components/MakeLabel/index.vue'
import { getPlat } from '@/api/sourceManage/sourceManage'

export default {
  name: 'addCustomer',
  components: {
    SelectUser,
    SelectCus,
    MakeLabel,
  },
  props: {
    // 添加标签显隐
    visible: {
      type: Boolean,
      default: false,
    },
    //弹窗标题
    title: {
      type: String,
      default: '',
    },
    //修改客户ID
    customerInfo: {
      type: Object,
      default: {},
    },
    //修改客户Id
    changeCustomerId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      distributeEmployeProps: {},
      addForm: {
        phone: undefined,
        weGroupTagVOS: undefined,
        distributeEmploye: undefined,
        remark: undefined,
        insuranceType: undefined,
        platformId: undefined,
      },
      rules: {
        phone: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            trigger: 'blur',
            message: '手机号码位数需为11位，请核实',
          },
          {
            pattern: /^[1]([3-9])[0-9]{9}$/,
            message: '手机号码必需以13、14、15、16、17、18、19开头，请核实',
            trigger: 'blur',
          },
        ],
        platformId: [
          {
            required: true,
            trigger: 'change',
            message: '请选择获客平台',
          },
        ],
      },
      //备注栏输入字数
      remarkInputNum: 0,
      //员工数据下拉框
      distributeEmployeList: [],
      //修改时员工ID
      batchAddingId: '',
      tableDataName: [],
      selectUserVisible: false,
      scrmPersonSopUserRels: [],
      makeLabelList: [],
      platformList: [],
      scrmBussLineId: 0,
      makeLabelVisible: false,
    }
  },
  computed: {
    addVisible: {
      get() {
        if (this.visible) {
          this.$nextTick(() => {
            this.reset()
            this.changeLine(localStorage.getItem('InsuranceType'))
            console.log(
              this.$props.customerInfo,
              '查看一下这个带过来的值都有啥'
            )
            if (this.$props.changeCustomerId) {
              let arr = [
                'phone',
                'weGroupTagVOS',
                'distributeEmploye',
                'remark',
              ]
              arr.forEach((item) => {
                if (item == 'distributeEmploye') {
                  let custArr = []
                  custArr.push({
                    userId: this.$props.customerInfo.distributeEmployeId,
                    userName: this.$props.customerInfo.distributeEmploye,
                  })
                  // this.addForm[item] = custArr;
                  this.scrmPersonSopUserRels = custArr
                  console.log(custArr)
                }
                //           else if (
                //             item == 'weGroupTagVOS' &&
                //             this.$props.customerInfo.customerTagList.length > 0
                //           ) {
                //             this.addForm[item] = ''
                //             this.$props.customerInfo.customerTagList.forEach(
                //               (item, index) => {
                //                 // index <
                //                 // this.$props.customerInfo.customerTagList.length - 1
                //                 //   ? (this.addForm.weGroupTagVOS += item + ';')
                //                 //   : (this.addForm.weGroupTagVOS += item)
                //                 this.addForm.weGroupTagVOS += item + ';'
                //               }
                //             )
                // // console.log('this.addForm.weGroupTagVOS',this.addForm.weGroupTagVOS);
                //             this.makeLabelList = this.$props.customerInfo.customerTagList
                //           }
                else {
                  this.addForm[item] = this.$props.customerInfo[item]
                }
              })
              if (this.addForm.remark) {
                this.remarkInputNum = this.addForm.remark.length
              }
            }
          })
        }
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      },
    },
  },
  methods: {
    changeLine(data) {
      this.platformList = []
      getPlat({ scrmBussLineId: data }).then((res) => {
        this.platformList = res.rows || []
      })
    },
    onClose() {
      this.$refs['addForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    //选中的员工数据
    selectUserConfirm(value) {
      console.log(value, '看下这个值')
      if (value && value.length > 1) {
        this.$message.error('只支持选中一个员工')
        this.selectUserVisible = true
      } else {
        this.scrmPersonSopUserRels = []
        value.forEach((item) => {
          this.scrmPersonSopUserRels.push({
            ...item,
          })
        })
      }
    },
    //提交客户信息
    handelConfirm() {
      console.log('this.addForm.weGroupTagVOS', this.addForm.weGroupTagVOS)
      // return
      console.log(
        this.scrmPersonSopUserRels,
        'scrmPersonSopUserRels',
        '@@@@@@@###########'
      )
      if (+this.scrmPersonSopUserRels.length === 0) {
        this.$message.error('请至少选择一位员工！')
      } else {
        this.$refs['addForm'].validate((valid) => {
          if (valid) {
            // this.addForm.distributeEmploye = this.addForm.distributeEmploye[1];
            // if (this.addForm.weGroupTagVOS) {
            //   this.addForm.weGroupTagVOS = this.addForm.weGroupTagVOS.replace(
            //     /^\s*|\s*$/g,
            //     ''
            //   )
            //   if (
            //     this.addForm.weGroupTagVOS.indexOf(';') != -1 ||
            //     this.addForm.weGroupTagVOS.indexOf('；') != -1
            //   ) {
            //     let tagList = []
            //     let arr = this.addForm.weGroupTagVOS.split(/[；;]/g)
            //     arr.forEach((item) => {
            //       item = String(item).replace(/^\s*|\s*$/g, '')
            //       if (tagList.indexOf(item) == -1 && item != '') {
            //         tagList.push(item)
            //       }
            //     })
            //     this.addForm.weGroupTagVOS = tagList
            //   } else {
            //     let tagList = []
            //     tagList.push(this.addForm.weGroupTagVOS)
            //     this.addForm.weGroupTagVOS = tagList
            //   }
            // }
            this.addForm.distributeEmploye =
              this.scrmPersonSopUserRels[0].userId
            this.addForm.remark = this.addForm.remark || ''
            // this.addForm.weGroupTagVOS = this.makeLabelList || []
            return new Promise((reslove, reject) => {
              if (this.$props.changeCustomerId) {
                this.addForm.batchAddingId = this.$props.changeCustomerId
                updateAdding(this.addForm)
                  .then((res) => {
                    console.log(res)
                    this.msgSuccess('修改成功')
                    this.$parent.getListFn()
                    this.close()
                  })
                  .catch((res) => {
                    reject()
                    this.close()
                  })
              } else {
                add(this.addForm)
                  .then((res) => {
                    this.msgSuccess('新增成功')
                    this.$parent.getListFn()
                    this.close()
                  })
                  .catch(() => {
                    reject()
                    this.close()
                  })
              }
            })
          } else {
            this.msgError('您还未录入完成，请核对后提交！')
          }
        })
      }
    },
    //删除员工
    handleClose(item) {
      this.scrmPersonSopUserRels = this.scrmPersonSopUserRels.filter((x) => {
        return x.userId != item.userId
      })
    },
    //备注栏输入字数
    remarkChange() {
      let num = this.addForm.remark.length
      if (num <= 64 && num > 0) {
        this.remarkInputNum = num
      } else {
        this.remarkInputNum = 0
      }
    },

    /** 问卷重置 */
    reset() {
      this.addForm.phone = undefined
      this.addForm.weGroupTagVOS = undefined
      this.addForm.distributeEmploye = undefined
      this.addForm.remark = undefined
      this.addForm.platformId = undefined
      this.scrmPersonSopUserRels = []
    },

    //添加员工
    handleClick() {
      // let arr = []
      // if (this.scrmPersonSopUserRels) this.scrmPersonSopUserRels.forEach(item => arr.push(item))
      // this.tableDataName = arr
      this.tableDataName = this.scrmPersonSopUserRels || []
      this.selectUserVisible = true
    },

    //打开标签弹窗
    handleClickLabel() {
      this.makeLabelVisible = true
    },

    // 标签弹窗点击确定按钮
    makeLabelConfirm(value) {
      this.addForm.weGroupTagVOS = value
      if (this.addForm.weGroupTagVOS) {
        this.addForm.weGroupTagVOS = this.addForm.weGroupTagVOS.replace(
          /^\s*|\s*$/g,
          ''
        )
        if (
          this.addForm.weGroupTagVOS.indexOf(';') != -1 ||
          this.addForm.weGroupTagVOS.indexOf('；') != -1
        ) {
          let tagList = []
          let arr = this.addForm.weGroupTagVOS.split(/[；;]/g)
          arr.forEach((item) => {
            item = String(item).replace(/^\s*|\s*$/g, '')
            if (tagList.indexOf(item) == -1 && item != '') {
              tagList.push(item)
            }
          })
          this.makeLabelList = tagList
        } else {
          let tagList = []
          tagList.push(this.addForm.weGroupTagVOS)
          this.makeLabelList = tagList
        }
      }
    },

    // 关闭已经添加的标签
    handleCloseLabel(item) {
      this.makeLabelList = this.makeLabelList.filter((x) => {
        return x != item
      })
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep.el-form-item {
  margin-top: 4px !important;
}

//.weGroupTagVOS {
//  position: relative;
//}
//
//.inputInfo {
//  position: absolute;
//  color: #082aff;
//  font-size: 12px;
//  top: 50px;
//  left: 104px;
//  line-height: 22px;
//  margin-bottom: 8px;
//}

#remarkInput {
  position: relative;
}

#remarkInputNum {
  position: absolute;
  right: 8px;
  bottom: -4px;
}

::v-deep.el-form-item.is-error {
  margin-bottom: 8px !important;
}

// 必录框前面的 '*'
.showRedRules {
  ::v-deep.el-form-item__label:before {
    content: '*';
    color: #e74e59;
    margin-right: 4px;
  }
}
</style>
